package net.mihome.app.ui;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.bean.User;
import net.mihome.app.common.StringUtils;
import net.mihome.app.common.UIHelper;
import net.mihome.app.utils.LoginResponseHandler;

/**
 * 用户登录对话框
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class LoginActivity extends BaseActivity{
	
	private ViewSwitcher mViewSwitcher;
	private Button btn_login;
	private View btn_register;
	private AutoCompleteTextView mAccount;
	private EditText mPwd;
	private AnimationDrawable loadingAnimation;
	private View loginLoading;
	private CheckBox chb_rememberMe;
	private View resetPasswordView;
	private int curLoginType;
	private InputMethodManager imm;
	private AppContext appContext;// 全局Context
	
	public final static int LOGIN_OTHER = 0x00;
	public final static int LOGIN_MAIN = 0x01;
	public final static int LOGIN_SETTING = 0x02;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        appContext = (AppContext) getApplication();
		// 网络连接判断
		if (!appContext.isNetworkConnected())
			UIHelper.ToastMessage(this, R.string.network_not_connected);
		// 初始化登陆
//		appContext.initLoginInfo();
		if(appContext.checkLogin()){
			//如果能够找到cookie，直接跳转到首页
			afterLoignRedictTo();
			finish();
            return ;
		}
        setContentView(R.layout.login_activity);

        imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
        
        curLoginType = getIntent().getIntExtra("LOGINTYPE", LOGIN_OTHER);
        resetPasswordView=findViewById(R.id.login_checkbox_rest_password);
        mViewSwitcher = (ViewSwitcher)findViewById(R.id.logindialog_view_switcher);       
        loginLoading = (View)findViewById(R.id.login_loading);
        mAccount = (AutoCompleteTextView)findViewById(R.id.login_account);
        mPwd = (EditText)findViewById(R.id.login_password);
        chb_rememberMe = (CheckBox)findViewById(R.id.login_checkbox_rememberMe);
        //从缓存中读取出用户上次输入的用户名，填充到用户名框中
        String userNameLast=AppContext.getInstance().getProperty("last.username");
        if(userNameLast!=null){
            mAccount.setText(userNameLast);
            mPwd.setFocusable(true);
            mPwd.setFocusableInTouchMode(true);
            mPwd.requestFocus();
        }
        btn_login = (Button)findViewById(R.id.login_btn_login);
        btn_login.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				//隐藏软键盘
				imm.hideSoftInputFromWindow(v.getWindowToken(), 0);  
				
				String account = mAccount.getText().toString();
				String pwd = mPwd.getText().toString();
				boolean isRememberMe = chb_rememberMe.isChecked();
				//判断输入
				if(StringUtils.isEmpty(account)){
					UIHelper.ToastMessage(v.getContext(), getString(R.string.msg_login_email_null));
					return;
				}
				if(StringUtils.isEmpty(pwd)){
					UIHelper.ToastMessage(v.getContext(), getString(R.string.msg_login_pwd_null));
					return;
				}
				
		        loadingAnimation = (AnimationDrawable)loginLoading.getBackground();
		        loadingAnimation.start();
		        mViewSwitcher.showNext();
		        //将用户输入的用户名记录到缓存中，避免用户登录失败后需要重新输入
                AppContext.getInstance().setProperty("last.username",account);
		        login(account, pwd, isRememberMe);
			}
		});
        //跳转到登陆
        btn_register=findViewById(R.id.login_btn_regedit);
        btn_register.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent=getIntent().setClass(LoginActivity.this,RegisterPhone.class);
				startActivity(intent);
			}
		});
        //跳转到找回密码
        resetPasswordView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent=getIntent().setClass(LoginActivity.this,RestPassWordPhoneActivity.class);
				startActivity(intent);
			}
		});
        //是否显示登录信息
        AppContext ac = (AppContext)getApplication();
        User user = ac.getLoginInfo();
        if(user==null || !user.isRememberMe()) return;
        if(!StringUtils.isEmpty(user.getAccount())){
        	mAccount.setText(user.getAccount());
        	mAccount.selectAll();
        	chb_rememberMe.setChecked(user.isRememberMe());
        }
        if(!StringUtils.isEmpty(user.getPwd())){
        	mPwd.setText(user.getPwd());
        }
    }
    public static final int LOGIN_FAILED=1;
    public static final int LOGIN_SUCCESS=2;
    //登录验证
    private void login(final String account, final String pwd, final boolean isRememberMe) {
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
                switch (msg.what){
                    case LOGIN_FAILED:{
                        AppContext.getInstance().cleanCookie();
                        mViewSwitcher.showPrevious();
                        UIHelper.ToastMessage(LoginActivity.this, getString(R.string.msg_login_fail)+msg.obj);
                        break;
                    }
                    case LOGIN_SUCCESS:{
                        AppContext.getInstance().loadContractList(new LoginResponseHandler() {
                            @Override
                            public void onSuccess(User user) {
                                afterLoignRedictTo();
                                finish();
                            }

                            @Override
                            public void onFailed(String msg) {
                                Toast.makeText(LoginActivity.this,"无法获取好友列表"+msg,Toast.LENGTH_SHORT).show();
                                AppContext.getInstance().cleanCookie();
                                mViewSwitcher.showPrevious();
                            }
                        });
                        break;
                    }
                    default:{
                        Toast.makeText(LoginActivity.this,"登录失败",Toast.LENGTH_SHORT).show();
                        break;
                    }
                }
			}
		};
        appContext.loginAsync(account,pwd,new LoginResponseHandler() {
            @Override
            public void onSuccess(User user) {
                Message message=new Message();
                message.what=LOGIN_SUCCESS;
                message.obj=user;
                handler.sendMessage(message);
            }

            @Override
            public void onFailed(String msg) {
                Message message=new Message();
                message.what=LOGIN_FAILED;
                message.obj=msg;
                handler.sendMessage(message);
            }
        });
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if(keyCode == KeyEvent.KEYCODE_BACK) {
    		this.onDestroy();
    	}
    	return super.onKeyDown(keyCode, event);
    }
    public void afterLoignRedictTo(){
    	Intent intent = new Intent(LoginActivity.this, MainPager.class);
		intent.putExtra("LOGIN", true);
		startActivity(intent);
    }


}
